<?php
namespace app\api\model;
use think\Model;
use think\facade\Db;
use app\admin\model\Admin;
use app\api\model\Category;
class Goods extends Model
{
    protected $pk = 'id';
    
    public function category()
    {
        // 关联Admin模型，当前表的admin_id对应Admin表的主键（默认id）
        return $this->belongsTo(Category::class, 'category_id', 'id');
    }
    public static function getGoodsList($page=1,$pageSize=10,$keyword='',$category='')
    {
        $query = self::with(['category' => function($adminQuery) {
            $adminQuery->field('id,category_name'); 
        }]);
        if($category) 
            $query = $query->where('category_id',$category);
        if (!empty($keyword)) {
            $query=$query->where(function ($q) use ($keyword) {
                $q->where('goods_name', 'like', "%{$keyword}%");
            });
        }

        $list = $query->order('create_time','desc')
                      ->paginate([
                        'list_rows' => $pageSize,
                        'page' => $page
                    ]);
        $data = $list;
        return ['code'=>200,'msg'=>'success','data'=>$data];
    }
    public static function getGoodsDetail($id)
    {
        $goods = self::with(['category' => function($adminQuery) {
            $adminQuery->field('id,category_name'); 
        }])->find($id);
        if(empty($goods))
            return ['code'=>400,'msg'=>'商品不存在'];
        $data = $goods;
        return ['code'=>200,'msg'=>'success','data'=>$data];
    }
    

}